#!/usr/bin/env python3
"""
KVM-QEMU-OpenHarmony 虚拟化管理主程序
版本：2.1
功能：虚拟机生命周期管理、跨平台部署、交互式配置
"""

import argparse
import logging
import sys
import platform
from pathlib import Path
from core.vm_manager import OpenHarmonyVM, VMState
from utils.env_check import check_kvm_support, check_hyperv_status
from utils.disk_manager import DiskBuilder
from utils.network_setup import NetworkConfigurator

# 配置日志记录
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('runtime.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

DEFAULT_CONFIG = Path('configs/vm_config.yaml')

class OHVMController:
    """OpenHarmony 虚拟机控制器"""
    def __init__(self, config_path=None):
        self.config_path = config_path or DEFAULT_CONFIG
        self.vm = OpenHarmonyVM(str(self.config_path))
        self.network = NetworkConfigurator()
        self._init_platform()
        
    def _init_platform(self):
        """平台特定初始化"""
        self.os_type = platform.system()
        if self.os_type == 'Windows':
            check_hyperv_status()
        else:
            check_kvm_support()
            
    def start_interactive(self):
        """交互式启动菜单"""
        print("\n=== OpenHarmony 虚拟化管理器 ===")
        while True:
            print("\n操作选项:")
            print("1. 启动新虚拟机实例")
            print("2. 管理现有实例")
            print("3. 网络配置")
            print("4. 存储管理")
            print("5. 退出系统")
            
            choice = input("请输入选项 (1-5): ").strip()
            
            if choice == '1':
                self._handle_new_instance()
            elif choice == '2':
                self._manage_existing_vm()
            elif choice == '3':
                self.network_menu()
            elif choice == '4':
                self.storage_menu()
            elif choice == '5':
                print("感谢使用，再见！")
                sys.exit(0)
            else:
                print("无效输入，请重新选择")

    def _handle_new_instance(self):
        """新建实例流程"""
        print("\n=== 新建虚拟机实例 ===")
        self._customize_config()
        if self._confirm_action("确认创建新虚拟机？"):
            self.vm.create_vm()
            print("实例创建成功！启动中...")
            self.vm.start_vm()
            
    def _manage_existing_vm(self):
        """管理现有实例"""
        print("\n=== 虚拟机管理 ===")
        print("1. 启动虚拟机")
        print("2. 停止虚拟机")
        print("3. 重启虚拟机")
        print("4. 创建快照")
        print("5. 恢复快照")
        
        action = input("请选择操作 (1-5): ")
        vm_name = input("输入虚拟机名称: ")
        
        if action == '1':
            self.vm.start_vm(vm_name)
        elif action == '2':
            self.vm.stop_vm(vm_name)
        elif action == '3':
            self.vm.reboot_vm(vm_name)
        elif action == '4':
            snap_name = input("输入快照名称: ")
            self.vm.create_snapshot(vm_name, snap_name)
        elif action == '5':
            snap_name = input("输入要恢复的快照名: ")
            self.vm.restore_snapshot(vm_name, snap_name)

    def network_menu(self):
        """网络配置菜单"""
        print("\n=== 网络配置 ===")
        print("1. 创建桥接网络")
        print("2. 配置NAT网络")
        print("3. 查看当前配置")
        
        choice = input("请选择操作 (1-3): ")
        if choice == '1':
            bridge_name = input("输入桥接接口名称 [默认: ohos-br0]: ") or "ohos-br0"
            self.network.create_bridge(bridge_name)
        elif choice == '2':
            self.network.setup_nat()

    def storage_menu(self):
        """存储管理菜单"""
        print("\n=== 存储管理 ===")
        print("1. 创建新磁盘镜像")
        print("2. 扩展现有磁盘")
        print("3. 转换磁盘格式")
        
        choice = input("请选择操作 (1-3): ")
        disk_builder = DiskBuilder()
        
        if choice == '1':
            path = input("磁盘路径 (例如: /data/disk.qcow2): ")
            size = input("大小 (例如: 64G): ")
            disk_builder.create_disk(path, size)
        elif choice == '2':
            path = input("现有磁盘路径: ")
            extra_size = input("扩展容量 (例如: +20G): ")
            disk_builder.expand_disk(path, extra_size)

    def _customize_config(self):
        """交互式配置向导"""
        print("\n=== 自定义配置 ===")
        new_config = {}
        new_config['name'] = input("虚拟机名称: ")
        new_config['cpus'] = int(input("CPU核心数 [默认4]: ") or 4)
        new_config['memory'] = input("内存大小 (例如 8GiB): ") or "8GiB"
        new_config['vnc_port'] = int(input("VNC端口 [默认5900]: ") or 5900)
        # 保存临时配置
        self._save_temp_config(new_config)

    def _save_temp_config(self, config):
        """保存临时配置到YAML"""
        import yaml
        temp_path = Path('configs/temp_config.yaml')
        with open(temp_path, 'w') as f:
            yaml.safe_dump(config, f)
        self.config_path = temp_path

    def _confirm_action(self, prompt):
        """确认操作对话框"""
        res = input(f"{prompt} [y/N]: ").lower()
        return res in ('y', 'yes')

def parse_args():
    """命令行参数解析"""
    parser = argparse.ArgumentParser(description="OpenHarmony 虚拟化管理器")
    parser.add_argument('--cli', action='store_true', 
                      help="命令行模式（禁用交互界面）")
    parser.add_argument('--start', metavar='VM_NAME', 
                      help="启动指定虚拟机")
    parser.add_argument('--stop', metavar='VM_NAME',
                      help="停止运行中的虚拟机")
    parser.add_argument('--create', action='store_true',
                      help="创建新虚拟机实例")
    return parser.parse_args()

def main():
    args = parse_args()
    controller = OHVMController()
    
    try:
        if args.cli or args.start or args.stop:
            # 命令行模式
            if args.start:
                controller.vm.start_vm(args.start)
            elif args.stop:
                controller.vm.stop_vm(args.stop)
            elif args.create:
                controller._handle_new_instance()
        else:
            # 交互模式
            controller.start_interactive()
    except Exception as e:
        logger.error(f"运行错误: {str(e)}", exc_info=True)
        sys.exit(1)

if __name__ == "__main__":
    main()
